//
//  StatusListViewModel.swift
//  SinaWeibo
//
//  Created by 张子国 on 15/11/19.
//  Copyright © 2015年 张子国. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking
import SVProgressHUD
import SDWebImage
class StatusListViewModel: NSObject {
    
    //加载微博首页数据
    
    class  func loadData ( since_id : Int, max_id : Int, finished: (array : [Status]?) ->()) {
        //实例化AFN
//      let AFN = AFHTTPSessionManager()
        let urlString = "2/statuses/home_timeline.json"
        
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus(AppErrprlip)
            return
        }
        var parameters = ["access_token" : token]
        
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools .sharedTools .requestJsonDict(HTTPMethod.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(array: nil)
                return
            }
            
            if let arr = result!["statuses"] as? [[String : AnyObject]] {
                //定义模型
                var list = [Status]()
                
                for item in arr {
                    //字典转模型
                    let s = Status(dict: item)
                    list .append(s)
                    
                }
                //回调
                finished(array: list)
                
                //获取单张缓存图片
                cacheStatusImage(list, finished: finished)
                
                
            }
        }
    }
    private class func cacheStatusImage(array :[Status],finished: (array :[Status]?) -> ()) {
        
        if array.count == 0 {
            finished(array: nil)
            return
        }
        //创建群组
        let group = dispatch_group_create()
        
        //遍历
        for s in array {
            if let imageUrl = s.imageURLs {
                if imageUrl.count != 1 {
                    continue
                }
                //一定取到单张图片
                for url in imageUrl {
                    
                    //进组队列
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _ , _ , _, _) -> Void in
                        print("单张下载")
                        
                    //异步任务离开群组
                    dispatch_group_leave(group)
                    })
                }
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //主线程回调
            print("下载完成")
            finished(array: array)
        }
    }
    
   }



